package org.techmore.biz;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.techmore.R;
import org.techmore.utils.DatabaseHelper;
import org.techmore.utils.DownloadNoStoreHandler;
import org.techmore.utils.ImageDownloadHandler;
import org.techmore.utils.PropertiesUtil;
import org.techmore.vo.CouponDetailsVO;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class ConsultCouponDetailsActivityDataHandler {
	
	private static ConsultCouponDetailsActivityDataHandler consultCouponDetailsActivityDataHandler = new ConsultCouponDetailsActivityDataHandler();
	
	public static ConsultCouponDetailsActivityDataHandler getInstance(){
		return consultCouponDetailsActivityDataHandler;
	}
	
	private Handler dataHandler = null;
	private CouponDetailsVO couponDetailsVO = null;
	
	private SAXParserFactory factory = null;
	private SAXParser parser = null;
	
	
	
	public int storeCoupon(Context context){
		int success = 0;
		if(null != couponDetailsVO){
			String databaseName = PropertiesUtil.getInstance().getValue("databaseName");
			SQLiteDatabase sqLiteDatabase = null;
			Cursor cursor = null;
			int rowNum = 0;
			String querySql = "select count(*) as rowNum from couponDetailsVO where couponSeriesNo=? and couponNo=?";
			try {
				sqLiteDatabase = new DatabaseHelper(context, databaseName).getReadableDatabase();
				cursor = sqLiteDatabase.rawQuery(querySql,
					new String[]{couponDetailsVO.getCouponSeriesNo(),couponDetailsVO.getCouponNo()});
				while(cursor.moveToNext()){
					rowNum = cursor.getInt(cursor.getColumnIndex("rowNum"));
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.e("sqlite", e.getMessage());
			}finally{
				cursor.close();
				sqLiteDatabase.close();
				sqLiteDatabase = null;
			}
			if(rowNum<=0){
				String sql = "insert into couponDetailsVO (couponSeriesNo,store,subject,img48xUrl,couponImgUrl,startDate,endDate,introduction,couponNo,qrImageUrl) values (?,?,?,?,?,?,?,?,?,?)";
				try {
					sqLiteDatabase = new DatabaseHelper(context, databaseName).getWritableDatabase();
					sqLiteDatabase.execSQL(sql.toString(),
						new String[]{couponDetailsVO.getCouponSeriesNo(),couponDetailsVO.getStore(),
						couponDetailsVO.getSubject(),couponDetailsVO.getImg48xUrl(),couponDetailsVO.getCouponImgUrl(),couponDetailsVO.getStartDate(),
						couponDetailsVO.getEndDate(),couponDetailsVO.getIntroduction(),couponDetailsVO.getCouponNo(),couponDetailsVO.getQrImageUrl()});
					success = 1;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.e("sqlite", e.getMessage());
				}finally{
					sqLiteDatabase.close();
					sqLiteDatabase = null;
				}
			}else{
				success = 2;
			}
		}
		return success;
	}
	
	
	
	public void adapterCouponDetailsVO(String couponId,String img48xUrl,
			final TextView couponNameTextView,final TextView businessNameTextView,
			final TextView beginDateTextView,final TextView endDateTextView,
			final TextView commentTextView,final ImageView businessImageView){
		
		couponDetailsVO = new CouponDetailsVO();
		couponDetailsVO.setImg48xUrl(img48xUrl);
		
		try {
			factory = SAXParserFactory.newInstance();
			parser = factory.newSAXParser();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Log.e("ConsultCouponDetailsActivityDataHandler:", e.getMessage());
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Log.e("ConsultCouponDetailsActivityDataHandler:", e.getMessage());
		}
		
		String couponDetailsPath = PropertiesUtil.getInstance().getValue("qr_coupon_details_url");
		String couponQrCodePath = PropertiesUtil.getInstance().getValue("qr_coupon_qrcode_url");
		
		//&couponSeriesNo=201104180001201104180001
		couponDetailsPath = couponDetailsPath+"&couponSeriesNo="+couponId;
		couponQrCodePath = couponQrCodePath+"&couponSeriesNo="+couponId;
		
		
		dataHandler = new Handler(Looper.myLooper()){
    		public void handleMessage(android.os.Message msg) {
    			int sign = msg.what;
    			if(sign == 1){
    				String uri = String.valueOf(msg.obj);
        			try {
						parser.parse(new ByteArrayInputStream(uri.getBytes()), new CouponDetailsVO1_Handler());
					} catch (SAXException e) {
						Log.e("ConsultCouponDetailsActivityDataHandler:", e.getMessage());
					} catch (IOException e) {
						Log.e("ConsultCouponDetailsActivityDataHandler:", e.getMessage());
					}
					couponNameTextView.setText(couponDetailsVO.getSubject());
					businessNameTextView.setText(couponDetailsVO.getStore());
					beginDateTextView.setText(couponDetailsVO.getStartDate());
					
					Handler imageHandler = new Handler(Looper.myLooper()){
						@Override
						public void handleMessage(Message msg) {
							// TODO Auto-generated method stub
							Bitmap bitmap = (Bitmap) msg.obj;
							businessImageView.setImageBitmap(bitmap);
						}
					};
					String imageuri = String.valueOf(couponDetailsVO.getCouponImgUrl());
//					System.out.println(couponDetailsVO.getCouponImgUrl());
					imageHandler.postDelayed(new ImageDownloadHandler(imageuri, 
							imageHandler, imageuri.substring(imageuri.lastIndexOf("/"), imageuri.length())), 100);
					
					if(null == couponDetailsVO.getEndDate() || couponDetailsVO.getEndDate().equals("")){
						endDateTextView.setText(R.string.couponValidityTime);
					}else{
						endDateTextView.setText(couponDetailsVO.getEndDate());
					}
					commentTextView.setText(couponDetailsVO.getIntroduction());
    			}
    			if(sign == 2){
    				String uri = String.valueOf(msg.obj);
        			try {
						parser.parse(new ByteArrayInputStream(uri.getBytes()), new CouponDetailsVO2_Handler());
					} catch (SAXException e) {
						Log.e("ConsultCouponDetailsActivityDataHandler:", e.getMessage());
					} catch (IOException e) {
						Log.e("ConsultCouponDetailsActivityDataHandler:", e.getMessage());
					}
//					try {
//						businessImageView.setImageBitmap(
//								QRCodeEncoder.encodeAsBitmap(couponDetailsVO.getCouponNo(),BarcodeFormat.QR_CODE, 260, 260));
//					} catch (WriterException e) {
//						Log.e("ConsultCouponDetailsActivityDataHandler:", e.getMessage());
//					}
    			}
    			
    		};
    	};
    	dataHandler.postDelayed(new DownloadNoStoreHandler(couponDetailsPath, dataHandler, 1), 100);
    	dataHandler.postDelayed(new DownloadNoStoreHandler(couponQrCodePath, dataHandler, 2), 200);
    	
	}
	
	
	public class CouponDetailsVO1_Handler extends DefaultHandler{
		public CouponDetailsVO1_Handler(){}
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
		}
		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			
			if("couponAdvDetail".equals(qName) || "couponAdvDetail".equals(localName) ){
				couponDetailsVO.setCouponSeriesNo(attributes.getValue("couponSeriesNo"));
				couponDetailsVO.setStore(attributes.getValue("store"));
				couponDetailsVO.setSubject(attributes.getValue("subject"));
				couponDetailsVO.setStartDate(attributes.getValue("startDate"));
				couponDetailsVO.setCouponImgUrl(attributes.getValue("couponImgUrl"));
				couponDetailsVO.setEndDate(attributes.getValue("endDate"));
				couponDetailsVO.setIntroduction(attributes.getValue("introduction"));
			}
		}
		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
		}
		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			super.endElement(uri, localName, qName);
			if("couponAdvDetail".equals(qName) || "couponAdvDetail".equals(localName)){
//				couponDetailsVO = null;
			}
		}
		@Override
		public void characters(char[] ch, int start, int length) throws SAXException {
		}
	}
	
	
	public class CouponDetailsVO2_Handler extends DefaultHandler{
		public CouponDetailsVO2_Handler(){}
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
		}
		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			
			if("couponAquire".equals(qName) || "couponAquire".equals(localName) ){
				couponDetailsVO.setCouponNo(attributes.getValue("couponNo"));
				couponDetailsVO.setQrImageUrl(attributes.getValue("qrImageUrl"));
			}
		}
		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
		}
		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			super.endElement(uri, localName, qName);
			if("couponAquire".equals(qName) || "couponAquire".equals(localName)){
//				couponDetailsVO = null;
			}
		}
		@Override
		public void characters(char[] ch, int start, int length) throws SAXException {
		}
	}

}
